﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Radiation___IM.Users
{
    public class UserManager
    {
        private static UserManager _instance;

        public static void Init()
        {
            _instance = new UserManager();
        }

        public static UserManager Instance
        {
            get
            {
                return _instance;
            }
        }

        // Dynamic part

        private Hashtable m_users;
        private Int64 m_counter;

        public UserManager()
        {
            m_users = new Hashtable();
            m_counter = 0;
        }

        public User this[string nickname]
        {
            get
            {
                if (!m_users.ContainsKey(nickname))
                    return null;

                return (User)m_users[nickname];
            }
        }

        public void setNumberOfUsers(Int64 number)
        {
            m_counter = number;
        }

        /// <summary>
        /// This function will add the user and save it , if it's not a query from DatabaseLoad
        /// </summary>
        /// <param name="user">The user to add</param>
        /// <param name="database_load">Tell the function if it's a DatabaseLoad call or not</param>
        /// <returns>A standard rvalue</returns>
        public rvalue addUser(User user, bool database_load = false)
        {            
            if (m_users.ContainsKey(user.Nickname))
                return rvalue.USER_ALREADY_EXISTS;

            lock (m_users)
            {
                user.setId(m_counter);
                m_counter++;
                m_users.Add(user.Nickname, user);

                if (!database_load)
                    Data.DatabaseWriter.Instance.Queue(user.getFile());
            }

            return rvalue.USER_ADDED;
        }

        public rvalue removeUser(User user)
        {
            if (!m_users.ContainsKey(user.Nickname))
                return rvalue.USER_DOES_NOT_EXIST;

            lock (m_users)
            {
                m_users.Remove(user.Nickname);
            }

            return rvalue.USER_ADDED;
        }
    }
}
